package leetcode;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class LeetCode56 {

    public static void main(String[] args) {
        LeetCode56 leetCode56 = new LeetCode56();
        leetCode56.merge(new int[][]{{1, 4}, {0, 4}});
    }

    //最小数区间 最大数有区间
    //排序
    public int[][] merge(int[][] intervals) {
        Map<Integer, Integer> dict = new TreeMap<>();
        Map<Integer, Integer> map = new LinkedHashMap<>();
        int left, right, lastLeft = -1, lastRight = -1;
        for (int i = 0; i < intervals.length; i++) {
            left = intervals[i][0];
            right = intervals[i][1];
            dict.put(left, Math.max(right, dict.getOrDefault(left, -1)));
        }
        for (Map.Entry<Integer, Integer> entry : dict.entrySet()) {
            if (entry.getKey() <= lastRight) {
                lastRight = Math.max(entry.getValue(), lastRight);
            } else {
                if (lastLeft != -1 && lastRight != -1)
                    map.put(lastLeft, lastRight);
                lastLeft = entry.getKey();
                lastRight = entry.getValue();
            }
        }
        if (lastLeft != -1 && lastRight != -1)
            map.put(lastLeft, lastRight);
        int[][] result = new int[map.size()][2];
        int i = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            result[i][0] = entry.getKey();
            result[i][1] = entry.getValue();
            i++;
        }
        return result;
    }
//------------------------------------------------------------------
}
